
<template>

  <el-main>

    <el-form
        :model="searchModel"
        ref="searchForm"
        label-width="80px"
        :inline="true"
        size="small"
        >
        <el-form-item>
        <el-input v-model="searchModel.apiName" placeholder="请输入API名称"/>
        </el-form-item>
        <el-form-item>
        <el-button type="primary" icon="el-icon-search" @click="search()">查询</el-button>
        <el-button icon="el-icon-refresh-right">重置</el-button>
        <el-button type="success" icon="el-icon-plus" @click="openAddWindow()">新增</el-button>
        </el-form-item>
    </el-form>
        <!-- 数据表格 -->
        <el-table
        :data="tableData"
        border
        style="width: 100%">
            <el-table-column
              prop="id"
              label="id"
              width="100"
              align="center">
            </el-table-column>

            <el-table-column
              prop="apiName"
              label="api访问名称"
              width="100"
              align="center">
              <template slot-scope="scope">
                <el-tooltip placement="top" :open-delay=1000 :enterable="true">
                  <div slot="content">{{scope.row.remark}}</div>
                  <span>{{scope.row.apiName}}</span>
                </el-tooltip>
              </template>
            </el-table-column>

            <el-table-column
              prop="apiImg"
              label="网站logo"
              width="100"
              align="center">
                <template slot-scope="scope">
                  <el-image :src="scope.row.apiImg" @click="goToWebsite(scope.row)" style="width: 80%;height: 80%;border-radius: 10px;" ></el-image>
                </template>
            </el-table-column>

            <el-table-column
              prop="appUrl"
              label="api访问地址"
              width="180"
              align="center">
              <template slot-scope="scope">
                <el-link type="primary" :underline="false">{{scope.row.appUrl}}</el-link>
              </template>
            
            </el-table-column>
            <el-table-column
              prop="appIdValue"
              label="api账号"
              align="center">
              <template slot-scope="scope">
               <span @click="watchAppId(scope.row)">****</span>
             </template>
            </el-table-column>

            <el-table-column
              prop="appSecretValue"
              label="api秘钥"
              align="center">
              <template slot-scope="scope">
               <span @click="watchAppSecret(scope.row)">****</span>
             </template>
            </el-table-column>

            <el-table-column
              prop="state"
              label="是否启用"
              align="center">
              <template slot-scope="scope">
                  <el-switch
                    v-model="scope.row.state"
                    @change="changeState(scope.row)"
                    active-text="ON"
                    :active-value= 1
                    :inactive-value= 0
                    inactive-text="OFF">
                  </el-switch>
               </template>
            </el-table-column>

            <el-table-column label="操作" align="center" width="200">
              <template slot-scope="scope">
                  <el-button
                  icon="el-icon-edit"
                  type="primary"
                  size="small"
                  @click="handleEdit(scope.row)"
                  >编辑
                  </el-button>

                  <el-button
                  icon="el-icon-delete"
                  type="danger"
                  size="small"
                  @click="handleDelete(scope.row)"
                  >删除
                  </el-button>

               </template>
            </el-table-column>
  
    </el-table>
    <!-- 分页工具栏 -->
    <el-pagination
    background
    @size-change="handleSizeChange"
    @current-change="handleCurrentChange"
    :current-page="pageNo"
    :page-sizes="[10, 20, 30, 40, 50]"
    :page-size="10"
    layout="total, sizes, prev, pager, next, jumper"
    :total="total"
    >
    </el-pagination>

     <!-- 添加修改窗口 -->
     <system-dialog
      :title="apiDialog.title"
      :visible="apiDialog.visible"
      :width="apiDialog.width"
      :height="apiDialog.height"
      @onClose="onClose()"
      @onConfirm="onConfirm()"
    >
      <div slot="content">
        <el-form
          :model="apiObject"
          ref="apiForm"
          label-width="120px"
          :inline="true"
          size="small">

            <el-form-item label="id" prop="id" v-show="false">
              <el-input v-model="apiObject.id" ></el-input>
            </el-form-item>

            <el-form-item label="apiName" prop="apiName">
              <el-input v-model="apiObject.apiName" placeholder="填充api的名字"></el-input>
            </el-form-item>
             <!-- prop 属性的名字（K）  v-model 属性的值（V） -->
            <el-form-item label="官方网址" prop="website">
              <el-input v-model="apiObject.website" placeholder="填充api的官方网址"></el-input>
            </el-form-item>

            <el-form-item label="请求地址" prop="appUrl">
              <el-input v-model="apiObject.appUrl" placeholder="填充api的地址"></el-input>
            </el-form-item>

            <el-form-item label="是否启用" prop="state">
              <el-switch
                 
                    v-model="apiObject.state"
                    active-text="ON"
                    :active-value= 1
                    :inactive-value= 0
                    inactive-text="OFF">
                  </el-switch>
            </el-form-item>

            <el-form-item label="appIdKey" prop="appIdKey">
              <el-input v-model="apiObject.appIdKey" placeholder="填充账号的key" ></el-input>
            </el-form-item>

            <el-form-item label="appIdValue" prop="appIdValue">
              <el-input v-model="apiObject.appIdValue" placeholder="填充账号的value" type="password" ></el-input>
            </el-form-item>

            <el-form-item label="appSecretKey" prop="appSecretKey">
              <el-input v-model="apiObject.appSecretKey" placeholder="填充秘钥的key" ></el-input>
            </el-form-item>

            <el-form-item label="appSecretValue" prop="appSecretValue">
              <el-input v-model="apiObject.appSecretValue" placeholder="填充秘钥的value" type="password" ></el-input>
            </el-form-item>

            <el-form-item label="conditionKey" prop="conditionKey">
              <el-input v-model="apiObject.conditionKey" placeholder="填充查询条件的key"></el-input>
            </el-form-item>

            <el-form-item label="conditionType" prop="conditionType">
              <el-input v-model="apiObject.conditionType" placeholder="填充查询条件的类型"></el-input>
            </el-form-item>

           
            <el-form-item label="备注" prop="remark">
              <el-input
                type="textarea"
                :rows="3"
                placeholder="请输入内容"
                v-model="apiObject.remark">
              </el-input>
            </el-form-item>

            <!-- 网站logo -->
            <el-form-item label="网站logo">
                <el-upload
                :show-file-list="false"
                :on-success="handleImageSuccess"
                :before-upload="beforeImageUpload"
                class="avatar-uploader"
                :data="uploadHeader"
                :action="uploadURL+'/api/oss/file/upload?module=website'"
                >
                    <img v-if="apiObject.apiImg" :src="apiObject.apiImg">
                    <i v-else class="el-icon-plus avatar-uploader-icon"/>
                </el-upload>
            </el-form-item>

        

        </el-form>
      </div>
    </system-dialog>
    

  </el-main> 

</template> 

<script>
import SystemDialog from '@/components/system/Systemdialog'
import weatherApi from '@/api/resource/weather'
//导入token
import {getToken} from '@/utils/auth'

const IS_PROD = process.env.NODE_ENV === 'production'; //是否是生产模式
const preUrl = IS_PROD ? 'http://47.114.73.72:5577' : 'http://localhost:5577'; //是生产模式 '' ，不是则 '/api'

export default {
  name: "weather-api",
  components:{
      SystemDialog
    },
  data() {
    return {
      searchModel :{
          apiName: '',
          pageNo: 1,
          pageSize: 10,
      },
      uploadURL: preUrl ,
      tableData: [],//表格数据
      tableHeight: 0, //表格高度
      pageNo: 1, //当前页码
      pageSize: 10, //每页显示数量
      total: 0, //总数量
      //上传需要携带的数据
      uploadHeader:{"Authorization":getToken()},

      apiDialog: {
          title: "",      //窗口标题
          visible: false, //是否显示窗口
          width: 700,      //窗口宽度
          height: 420,    //窗口高度们
      },
      apiObject:{
          id: '', 
          apiName:'' ,  //api名称
          website:'',   //api官网   
          apiImg: '',   //官网logo
          appUrl: '',   //api调用地址
          state: 0,    //是否启用
          appIdKey: '',
          appIdValue: '',
          appSecretKey: '',
          appSecretValue: '',
          conditionKey: '',
          conditionType:'',
          belongs: '',
          remark: '',  //备注每个查询条件
      },
    }
  },
  methods :{
    tableRowClassName({row, rowIndex}) {
          if (rowIndex === 1) {
            return 'warning-row';
          } else if (rowIndex === 3) {
            return 'success-row';
          }
          return '';
        },

     /**
          * 打开添加窗口
          */
          openAddWindow() {
              //清空表单数据
              this.$resetForm("apiForm",this.apiObject);
              this.apiDialog.title = '新增API'//设置窗口标题
              this.apiDialog.visible = true//显示窗口
              this.apiObject.belongs = this.$store.getters.userId //当前登录用户id
        
          },
          /**
          * 窗口取消事件
          */
          onClose() {
              this.apiDialog.visible = false
          },
          /**
          * 窗口确认事件
          */
          onConfirm() {
            
              //表单验证
              this.$refs.apiForm.validate(async (valid)=>{
              if(valid){
                  let res = null;
                  //判断角色ID是否为空
                  if (this.apiObject.id === "") {
                      //新增
                      //发送添加请求
                  
                       res = await weatherApi.addWeatherApi(this.apiObject);
                  } else {
                      //发送修改请求
                      res = await weatherApi.editWeatherApi(this.apiObject);
                  }
                  //判断是否成功
                  if (res.success) {
                      this.$message.success(res.message);
                      //刷新
                      this.search(this.pageNo,this.pageSize);
                      //关闭窗口
                      this.apiDialog.visible = false;
                  } else {
                      this.$message.error(res.message);
                  }
              }
              });

          },
          /**
            * 删除
            */
            async handleDelete(row) {
                //发送删除请求
                let res = await weatherApi.deleteWeatherApi({ id: row.id });
                //判断是否成功
                if (res.success) {
                    //成功提示
                    this.$message.success(res.message);
                    //刷新
                    this.search();
                } else {
                    //失败提示
                    this.$message.error(res.message);
                }

            },

              /**
        * 编辑部门
        * @param row
        */
        handleEdit(row) {
          //数据回显
          this.$objCopy(row, this.apiObject);
          //设置窗口标题
          this.apiDialog.title = "编辑【"+this.apiObject.apiName+"】";
          //显示编辑部门窗口
          this.apiDialog.visible = true;
        },

        /**
        * 查询
        */
        async search() {
        
            this.searchModel.pageNo = this.pageNo;//当前页码
            this.searchModel.pageSize = this.pageSize;//每页显示数量
            //发送查询请求
            let res = await weatherApi.getWeatherApi(this.searchModel);
            //执行成功
            if (res.success) {
                //api列表
                this.tableData = res.data.records;
                //总数量
                this.total = res.data.total;
            }else{
              this.$message.error(res.data)
           }
        },

          /**
            * 当每页数量发生变化时触发该事件
            */
            handleSizeChange(size) {
            },
            /**
            * 当页码发生变化时触发该事件
            */
            handleCurrentChange(page) {
            },
            /**
            * 图片上传，上传成功回调
            * @param res
            * @param file
            */
            handleImageSuccess(res, file) {
                this.apiObject.apiImg = res.data
                // 强制重新渲染
                this.$forceUpdate()
            },
            /**
            * 上传校验
            * @param file
            * @returns {boolean}
            */
            beforeImageUpload(file) {
                const isLt2M = file.size / 1024 / 1024 < 2
                if (!isLt2M) {
                    this.$message.error('上传头像图片大小不能超过 2MB!')
                }
                return isLt2M
            },
            // 跳转到官网
            goToWebsite(row){
              window.open(row.website);
            },
            //改变启用状态
            changeState(row){
               weatherApi.updateState(row.id,row.state)
               .then((response) => {
                    //成功提示
                    this.$message.success(response.message); 
               }).catch((error)=>{
                    //成功提示
                    this.$message.error(error); 
               })

            },
            //查看AppId
            watchAppId(row){
                this.$alert( row.appIdValue == '' ? "<span style='color:#d3265dfb;font-size: 20px;'>无</span>": "<span style='color:#46e123;font-size: 20px;'>"+row.appIdValue+"</span>", {
                confirmButtonText: '确定',
                dangerouslyUseHTMLString: true,
                customClass: 'mybox',
                showClose: false,
                callback: action => {
                  this.$message({
                    type: 'success',
                    message: '已关闭'
                  });
               }
            })
          },
            //查看AppSecret
            watchAppSecret(row){
                this.$alert(row.appSecretValue == '' ? "<span style='color:#d3265dfb;font-size: 20px;'>无</span>": "<span style='color:#46e123 ;font-size: 20px; '>"+row.appSecretValue+"</span>" , {
                confirmButtonText: '确定',
                dangerouslyUseHTMLString: true,
                customClass: 'mybox',
                showClose: false,
                callback: action => {
                  this.$message({
                    type: 'success',
                    message: '已关闭'
                  });
               }
            })
          },
  },
    //初始化时调用
    created() {
        this.search();
    },

}
</script>

<style lang="scss">

  .mybox{
     text-align: center;
     font-family: "Georgia", Tahoma, Sans-Serif;
     line-height: 0px;
 
  }
  .el-table .warning-row {
    background: oldlace;
  }

  .el-table .success-row {
    background: #f0f9eb;
  }
  //用户头像
  .avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9 !important;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  }
  .avatar-uploader .el-upload:hover {
  border-color: #409EFF;

  }
  .avatar-uploader .avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
  }
  .avatar-uploader img {
  width: 178px;
  height: 178px;
  display: block;
  }



</style>